package edu.gatech.ors.mrsim.io.logging;

import java.io.File;
import java.io.FileNotFoundException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 * A simple interface for the rest of the application to logj4 loggers that
 * maintains some standards. TODO:write JUnit tests
 * 
 * Good intro to log4j:http://www.tutorialspoint.com/log4j/log4j_quick_guide.htm
 * More info: http://logging.apache.org/log4j/1.2/faq.html#a2.2 More info:
 * http:/
 * /ibswings.blogspot.com/2009/03/log4j-configuration-controlling-logging.html
 * TODO: open source license and such TODO: write Junit tests
 * 
 * @author Andrey Kurenkov (akurenkov3@gatech.edu)
 * @version 1.0
 */
public class Logging {
    private static Logging instance;
    private final Logger global = Logger.getLogger(Logging.class);
    private final static File LOG_FILE = new File("logs"
	    + System.getProperty("file.separator") + "log4j.properties");

    /**
     * Static Singleton getter. If instance null tries to instantiate the
     * instance and should succeed unless the logj4 has been tempered with.
     * 
     * @return the instance or null if the config file is not there.
     */
    public static Logging getInstance() {
	if (instance == null) {
	    try {
		instance = new Logging();
	    } catch (FileNotFoundException noFile) {
		noFile.printStackTrace();
	    }

	}
	return instance;
    }

    /**
     * Constructor used in first getInstance() call that sets up the log
     * options.
     * 
     * @throws FileNotFoundException
     *             if the config file is not in the logs folder, this is going
     *             to be thrown
     */
    public Logging() throws FileNotFoundException {
	PropertyConfigurator.configure(LOG_FILE.getAbsolutePath());
	// TODO: any other crucial configuration will likely be in here
    }

    /**
     * Gets a correctly names logger for any class. Also classes that perform
     * simple logging should get loggers through this.
     * 
     * @param forClass
     *            the class requesting a logger
     * @return a properly named and configured logger
     */
    public Logger getClassLogger(Class<?> forClass) {
	return Logger.getLogger(forClass);
    }

    /**
     * Returns the global logger for special cases where it is needed.
     * 
     * @return global logger.
     */
    public Logger getGlobal() {
	return global;
    }
}
